package com.paishen.peiniwan.frame.push;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.paishen.peiniwan.App;
import com.paishen.common.util.LogUtil;
import com.paishen.peiniwan.LauncherActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by peng on 2015/12/30.
 */
public class JPushReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        LogUtil.d("[JPushReceiver] onReceive : " + printBundle(bundle));
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            LogUtil.d("[JPushReceiver] ACTION_REGISTRATION_ID" + regId);
            // send the Registration Id to your server...
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            // 透传消息
            LogUtil.d("[JPushReceiver] ACTION_MESSAGE_RECEIVED");
//            try {
//                JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
//                int type = json.getInt("type");
//                long user_id = -1;
//                Iterator<String> it = json.keys();
//                while (it.hasNext()) {
//                    String keyName = it.next().toString();
//                    if (TextUtils.equals("user_id", keyName)) {
//                        user_id = json.getLong("user_id");
//                    }
//                }
//                com.paishen.peiniwan.database.User user = App.i().getUser();
//                if (user == null || user.getApp_auto_login() == null || !user.getApp_auto_login()) {
//                    LogUtil.e("[JPushReceiver] [empty login user] or [out of login]");
//                    return;
//                }
//                if (user_id > 0 && user_id != user.getId()) {
//                    LogUtil.e("[JPushReceiver] received [targetUserid:" + user_id + "] not [currUserid:" + user.getId() + "]");
//                    return;
//                }
//                PushController.getInstance().dealMessage(type, bundle.getString(JPushInterface.EXTRA_MESSAGE));
//            } catch (JSONException e) {
//                LogUtil.e("[JPushReceiver]" + e.getMessage());
//            }
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            LogUtil.d("[JPushReceiver] ACTION_NOTIFICATION_RECEIVED notificationId" + notificationId);
            try {
                JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                int type = json.getInt("type");
                long user_id = -1;
                String content = "";
                Iterator<String> it = json.keys();
                while (it.hasNext()) {
                    String keyName = it.next().toString();
                    if (TextUtils.equals("user_id",keyName)) {
                        user_id = json.getLong("user_id");
                    } else if (TextUtils.equals("content", keyName)) {
                        content = json.getString("content");
                    }
                }

                com.paishen.peiniwan.database.User user = App.i().getUser();
                if (user == null || user.getApp_auto_login() == null || !user.getApp_auto_login()) {
                    LogUtil.e("[JPushReceiver] [empty login user] or [out of login]");
                    return;
                }
                if (user_id > 0 && user_id != user.getId()) {
                    LogUtil.e("[JPushReceiver] received [targetUserid:" + user_id + "] not [currUserid:" + user.getId() + "]");
                    return;
                }
                PushController.getInstance().dealNotification(type, content);
            } catch (JSONException e) {
                LogUtil.e("[JPushReceiver]" + e.getMessage());
            }
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            LogUtil.d("[JPushReceiver] ACTION_NOTIFICATION_OPENED");
            //打开自定义的Activity
            Intent i = new Intent(context, LauncherActivity.class);
            i.putExtras(bundle);
            // i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(i);
        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            LogUtil.d("[JPushReceiver] ACTION_RICHPUSH_CALLBACK" + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            LogUtil.w("[JPushReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            LogUtil.d("[JPushReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        if (bundle == null) return "empty bundle";

        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                    LogUtil.i("This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    LogUtil.e("Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

}
